﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Configuration;
using System.Net.Http;
using Newtonsoft.Json.Linq; 
using LMB.AIP.Tests;

namespace LMB.AIP.Tests
{
    /// <summary>
    /// Rest帮助类
    /// </summary>
    public class RestHelper
    {
        public static readonly Encoding ParamEncoding = Encoding.UTF8;

        /// <summary>
        /// 基本URL 主要为地址
        /// </summary>
        public string BasicUrl { get; set; }

        /// <summary>
        /// 服务器IP地址或域名
        /// </summary>
        public string RootUrl { get; set; }

        public string Username { get; set; }
        public string Password  { get; set; }
        public string Openid  { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="basicUrl"></param>
        public RestHelper(string url="")
        {
            if (url == "")
            {
                this.BasicUrl = ConfigurationManager.AppSettings["ServerAddress"] + "/api/services/app/";
            }
            else 
            {
                this.BasicUrl = url;
            }
          //  RootUrl = ConfigurationManager.AppSettings["ServerAddress"];

            
        }

        private string CreateParameterString(Dictionary<string, string> param)
        {
            return string.Join("&", param.ToList().Select(p => string.Format("{0}={1}", p.Key, HttpUtility.UrlEncode(p.Value, ParamEncoding))));
        }

        /// <summary>
        /// 调用Get方法
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="metodName">方法名称</param>
        /// <returns>返回调用结果</returns>
        public object Get(string metodName)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BasicUrl + metodName);
            request.Method = "get";
            request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                return  null;
            }
            string json = GetResponseString(response);
            json = ClearStr(json);
           
            return JsonConvert.DeserializeObject(json);
        }

        /// <summary>
        /// 调用Get方法
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="metodName">方法名称</param>
        /// <param name="urlPara">参数</param>
        /// <returns>返回值</returns>
        public object Get(string metodName, Dictionary<string, string> paramDic)
        {
            if (paramDic != null && paramDic.Count > 0)
                return Get(metodName + "?" + CreateParameterString(paramDic));
            else
                return Get(metodName);
        }

     
        /// <summary>
        /// 获取并且转换字符串
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private string GetResponseString(HttpWebResponse response)
        {
            string json = null;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), ParamEncoding))
            {
                json = reader.ReadToEnd();
            }
            return json;
        }

        private string ClearStr(string str)
        {
            str = str.Trim(new char[] { '"' });
            str = str.Replace("\\\"", "\"");
            str = str.Replace(":\":", "\":");
            str = str.Replace("\\/", "/");
            return str;

        }

        public  void NotNull(object target, string parameterName)
        {
            if (parameterName == null)
                throw new ArgumentNullException("parameterName");
            if (target == null)
                throw new ArgumentNullException(parameterName);
        }



        /// <summary>
        /// Post 请求- 孔得亮
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual dynamic Post(string urlMethod,object request)
        {
            string content = JsonConvert.SerializeObject(request);
            string address = BasicUrl+urlMethod;
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, address);
            requestMessage.Headers.Add("Accept", "application/json");
            requestMessage.Headers.Add("Accept-Encoding", "UTF-8"); 
            requestMessage.Content = new StringContent(content, Encoding.UTF8, "application/json");

            //var client = System.Net.Http.HttpClientFactory.Create(new DecompressionHandler());
            var client = System.Net.Http.HttpClientFactory.Create(new DecompressionHandler());

            HttpResponseMessage response = client.SendAsync(requestMessage).Result;
            if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized)
                return new { Code = response.StatusCode };
            else
            {
                response.EnsureSuccessStatusCode();
                string responseContent = response.Content.ReadAsStringAsync().Result;
                dynamic result = JObject.Parse(responseContent);
                return result;
            }
        }

        /// <summary>
        /// 模拟浏览器登录后，请求接口
        /// </summary>
        /// <param name="urlMethod">接口地址</param>
        /// <param name="request">请求对象</param>
        /// <param name="username">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns>接口返回参数</returns>
        //public object ExecuteUser(string urlMethod, object request)
        //{
        //    Broswer broswer = new Broswer();
        //    if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Openid))
        //    {
        //        throw new ArgumentException("请先给用户名，密码，openid 赋值");
        //    }
        //    Loginmodel lg = new Loginmodel()
        //   {
        //       PhoneNumber = Username,
        //       OpenID = Openid,
        //       Password = Password
        //   };


        //    string loginInfo = JsonConvert.SerializeObject(lg);
        //    string requestURL = this.BasicUrl + urlMethod; 
        //   //第一步判断 是否登录成功。
        //    string loginResult = broswer.PostData(this.RootUrl + "/Account/Login?returnUrl=http://locallhost:6639", loginInfo, this.BasicUrl, "UTF-8", "Post", "application/json");
        //  dynamic loginresponse = JObject.Parse(loginResult);

        //  if (loginresponse.Success == false)
        //  {
        //       throw new ArgumentException("用户名或密码错误");
        //  } 

        //  //请求接口数据
        //  string content = JsonConvert.SerializeObject(request);
        //  string apiResult = broswer.PostData(requestURL, content, this.BasicUrl, "UTF-8", "Post", "application/json");

        //  dynamic result = JObject.Parse(apiResult);
        //  return result;
        //}


    }
}
